package com.sixmac.platform.service.impl;

import com.sixmac.core.base.service.BaseService;
import com.sixmac.core.plugins.dao.Blade;
import com.sixmac.core.plugins.dao.Db;
import com.sixmac.core.toolbox.CMap;
import com.sixmac.core.toolbox.ajax.AjaxResult;
import com.sixmac.core.toolbox.grid.BladePage;
import com.sixmac.core.toolbox.kit.DateKit;
import com.sixmac.module.*;
import com.sixmac.platform.service.RoomService;
import org.junit.Test;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by admin on 2018/9/3.
 */
@Service
public class RoomServiceImpl extends BaseService<Room> implements RoomService {

    public AjaxResult index(Landlord landlord, Integer page, Integer size) {
        BladePage<Map> bladePage = Db.paginate("select if((select count(*) " +
                "                from t_tenant_room where status = 1 and roomId " +
                "               = room.id)=0,1,2) s,  l.name,room.* from t_room room inner join t_landlord l on l.id = room.landlordId where l.id = " + landlord.getId(), null, page, size);
        return AjaxResult.initAjaxResult().setData(bladePage);
    }

    @Transactional
    public AjaxResult addTenant(Contract contract, Landlord landlord, Integer roomId, String startDate, String endDate) {
        Room room = this.findById(roomId);
        if (room == null)
            return error("房屋找不到");

        String phone = contract.getMobile();
        Tenant t = Blade.create(Tenant.class).findFirstBy("mobile=#{mobile}", getData("mobile", phone));
        //如果找不到手机号码，表示
        if (t == null) {
            //创建租户
            t = new Tenant();
            t.setIdCard(contract.getIdCard());
            t.setIdCardFront(contract.getIdCardFront());
            t.setIdCardReverse(contract.getIdCardReverse());
            t.setMobile(contract.getMobile());
            t.setName(contract.getName());
            t.setSex(contract.getSex());
            t.setCreateDate(new Date());
            t.setStatus(1);
            Integer id = Blade.create(Tenant.class).saveRtId(t);
            t.setId(id);
        } else {
            contract.setTentantId(t.getId());
        }

        TenantRoom tr = Blade.create(TenantRoom.class).findFirstBy(" status = 1 and tenantId ="+t.getId(),null);

        if (tr!=null){
            return error("该用户已经入住。");
        }

        tr = Blade.create(TenantRoom.class).findFirstBy(" approve = 3 and tenantId ="+t.getId(),null);

        if (tr!=null&&tr.getRoomId()!=roomId){
            return error("该用户已经申请其他房间。");
        }

        if (tr!=null&&tr.getRoomId()==roomId) {
            return error("该用户已经申请，请去审核。");
        }

        Blade.create(Contract.class).save(contract);

        TenantRoom tenantRoom = new TenantRoom();
        tenantRoom.setContract(contract.getContract());
        tenantRoom.setRoomId(roomId);
        tenantRoom.setTenantId(t.getId());
        tenantRoom.setLandlordId(landlord.getId());
        tenantRoom.setCreateDate(new Date());
        tenantRoom.setStartDate(DateKit.parseTime(startDate+" 00:00:00"));
        tenantRoom.setEndDate(DateKit.parseTime(endDate+" 23:59:59"));
        tenantRoom.setApprove(1);
        tenantRoom.setStatus(1);
        tenantRoom.setKey(room.getKey() == null ? "" : room.getKey());
        Integer ids = Blade.create(TenantRoom.class).saveRtId(tenantRoom);

        contract.setStartTime(tenantRoom.getStartDate());
        contract.setEndTime(tenantRoom.getEndDate());
        contract.setTenantRoomId(ids);
        contract.setHandCard(t.getHandCard());
        contract.setStatus(0);//入住
        contract.setTentantId(t.getId());
        contract.setRoomId(room.getId());

//        LockManage lockManage = new LockManage();
//        LockUser lockUser = new LockUser();
//        lockUser.setDeviceCode(room.getLockNo());
//        lockUser.setUnlockWay("1");
//        lockUser.setLockUserInfo("100"+tenantRoom.getTenantId());
//        lockUser.setMsgId("100"+tenantRoom.getTenantId());
//        lockUser.setLockUserType("12");
//        lockUser.setStartDay(contract.getStartTime().getTime()/1000+"");
//        lockUser.setEndDay(contract.getEndTime().getTime()/1000+"");
//        lockUser.setUserFlag("100"+tenantRoom.getTenantId());
//        lockManage.addUser(lockUser);

        Blade.create(Contract.class).save(contract);

        return success("");
    }


    public AjaxResult getTenantByPhone(String phone) {
        Tenant t = Blade.create(Tenant.class).findFirstBy("mobile=#{mobile}", getData("mobile", phone));
        return new AjaxResult().setData(getData("tenant", t));
    }

    public AjaxResult getRoom(Landlord landlord, Integer roomId) {
        Room room = this.findById(roomId);
        if (room == null)
            return error("房屋找不到");
        if (room.getLandlordId().compareTo(landlord.getId()) != 0)
            return error("该房屋不属于你");

        String sql = "SELECT  tr.id trId,tr.roomId,tr.contract,IFNULL(c.name,t.name) name,ifnull(tr.fingerprint,-1) lockUserCode,IFNULL(c.sex,t.sex) sex\n" +
                ",IFNULL(c.mobile,t.mobile) mobile\n" +
                ",IFNULL(c.startTime,tr.startDate) startTime\n" +
                ",IFNULL(c.endTime,tr.endDate) endTime\n" +
                ",tr.`status`,tr.approve\n" +
                ",IFNULL(c.idCardFront,t.idCardFront) idCardFront "+
                ",IFNULL(c.idCardReverse,t.idCardReverse) idCardReverse "+
                ",IFNULL(c.handCard,t.handCard) handCard "+
                " from t_tenant_room tr \n" +
                "LEFT JOIN t_tenant t ON tr.tenantId = t.id\n" +
                "LEFT JOIN t_contact c ON c.tenantRoomId = tr.id\n" +
                "WHERE tr.roomId =   #{roomId} and (IFNULL(tr.`status`,0) != 2 and tr.approve != 2)";
        String sql2 = "SELECT  tr.id trId,tr.roomId,tr.contract,IFNULL(c.name,t.name) name,IFNULL(c.sex,t.sex) sex\n" +
                ",IFNULL(c.mobile,t.mobile) mobile\n" +
                ",IFNULL(c.startTime,tr.startDate) startTime\n" +
                ",IFNULL(c.endTime,tr.endDate) endTime\n" +
                ",tr.`status`,tr.approve\n" +
                ",IFNULL(c.idCardFront,t.idCardFront) idCardFront "+
                ",IFNULL(c.idCardReverse,t.idCardReverse) idCardReverse "+
                ",IFNULL(c.handCard,t.handCard) handCard "+
                " from t_tenant_room tr \n" +
                "LEFT JOIN t_tenant t ON tr.tenantId = t.id\n" +
                "LEFT JOIN t_contact c ON c.tenantRoomId = tr.id\n" +
                "WHERE tr.roomId =   #{roomId} and (IFNULL(tr.`status`,0) = 2 or tr.approve = 2)";
        List<Map> list = Db.selectList(sql, CMap.init().put("roomId", roomId));
        List<Map> history = Db.selectList(sql2, CMap.init().put("roomId", roomId));
        return new AjaxResult().setData(CMap.init().put("room",room).put("list", list).put("history", history));
    }

    public AjaxResult getRoomByAdmin(Landlord landlord, Integer roomId,Date time) {
        Room room = this.findById(roomId);
        if (room == null)
            return error("房屋找不到");
        if (room.getLandlordId().compareTo(landlord.getId()) != 0)
            return error("该房屋不属于你");

        Integer count = Db.queryInt("SELECT COUNT(*) from t_tenant_room tr where status = 1 and roomId = "+roomId,null);

        String sql = "SELECT ifnull(tr.isAdmin,0) isAdmin, tr.id trId,tr.roomId,tr.contract,IFNULL(c.name,t.name) name,IFNULL(c.sex,t.sex) sex\n" +
                ",IFNULL(c.mobile,t.mobile) mobile\n" +
                ",IFNULL(c.startTime,tr.startDate) startTime\n" +
                ",IFNULL(c.endTime,tr.endDate) endTime\n" +
                ",tr.`status`,tr.approve\n" +
                ",IFNULL(c.idCardFront,t.idCardFront) idCardFront "+
                ",IFNULL(c.idCardReverse,t.idCardReverse) idCardReverse "+
                ",IFNULL(c.handCard,t.handCard) handCard "+
                " from t_tenant_room tr \n" +
                "LEFT JOIN t_tenant t ON tr.tenantId = t.id\n" +
                "LEFT JOIN t_contact c ON c.tenantRoomId = tr.id\n" +
                "WHERE tr.roomId =   #{roomId} and (IFNULL(tr.`status`,0) != 2 and tr.approve != 2)";
        String sql2 = "SELECT  tr.id trId,tr.roomId,tr.contract,IFNULL(c.name,t.name) name,IFNULL(c.sex,t.sex) sex\n" +
                ",IFNULL(c.mobile,t.mobile) mobile\n" +
                ",IFNULL(c.startTime,tr.startDate) startTime\n" +
                ",IFNULL(c.endTime,tr.endDate) endTime\n" +
                ",tr.`status`,tr.approve\n" +
                ",IFNULL(c.idCardFront,t.idCardFront) idCardFront ,IFNULL(c.idCardReverse,t.idCardReverse) idCardReverse ,IFNULL(c.handCard,t.handCard) handCard  from t_tenant_room tr \n" +
                "LEFT JOIN t_tenant t ON tr.tenantId = t.id\n" +
                "LEFT JOIN t_contact c ON c.tenantRoomId = tr.id\n" +
                "WHERE tr.roomId =   44 and (IFNULL(tr.`status`,0) = 2 or tr.approve = 2)\n" +
                "and c.`status` = 1\n" +
                "and (c.outTime>'"+DateKit.getTime(time)+"')";
        List<Map> list = Db.selectList(sql, CMap.init().put("roomId", roomId));
        List<Map> history = Db.selectList(sql2, CMap.init().put("roomId", roomId));
        return new AjaxResult().setData(CMap.init().put("room",room).put("list", list).put("history", history).put("canOpen",count>0?0:1));
    }

    @Test
    public void te() {
        String s = "select i.id as roomInfoId," +
                " i.approve,i.status as istatus, l.name,l.sex," +
                " l.mobile,r.status,concat(l.idCardFront,',',l.idCardReverse,',',rt.contract) images," +
                "concat(rt.startDate,'~',rt.endDate) time from t_room r inner join " +
                "  t_room_tenant rt on rt.roomId = r.id inner join t_tenant l on l.id = rt.tenantId inner join " +
                " t_room_info i on i.tenantId = l.id where i.approve !=2 and r.id = #{roomId}  group by i.id";

        System.out.print(s);

    }


}
